//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:hktk_app/dao/practice_dao.dart';
import 'package:hktk_app/ienum/question/question_type_enum.dart';
import 'package:hktk_app/pages/question/child/stem_page.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';

import 'package:hktk_app/util/question_util.dart';
import 'package:hktk_app/util/sz_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/question/question_bottom_widget.dart';
import 'package:hktk_app/widget/question/question_title_widget.dart';

/// 自定义传递方法值
typedef PaperInit = Future<Map<String, dynamic>> Function();

/// 随机小测，试题页面
class QuestionPage extends StatefulWidget {
  /// 试题大题型相关加载方法
  final PaperInit paperInit;

  /// 加载试题数据方法
  final QuestionInit quesInit;

  const QuestionPage({
    super.key,
    required this.paperInit,
    required this.quesInit,
  });

  @override
  State<QuestionPage> createState() => _QuestionPageState();
}

class _QuestionPageState extends State<QuestionPage> {
  late BuildContext _context;

  late bool _init;

  /// 初始化数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 试题模式，ture-答题，false-背题
  late QuestionTypeEnum _type;

  /// 试题总数
  late int _total;

  /// 是否是答题卡跳转
  late bool _dtkTz;

  /// 页面控制器
  late PageController _pageController;

  /// 答题卡点击监听
  late StreamSubscription<EventQuestionOnDtk> _eventOnDtk;

  /// 夜间模式点击监听
  late StreamSubscription<EventQuestionOnYJMS> _eventOnYJMS;

  @override
  void initState() {
    super.initState();

    _init = true;
    _dtkTz = false;
    _total = 0;
    _type = QuestionTypeEnum.answer;
    _pageController = PageController(
      initialPage: 0,
      keepPage: true,
    );
    _futureInit = widget.paperInit();
    // 设置全局单列方法
    var szInfo = PracticeDao.getSzInfo();

    szUtilComm.szInfo = szInfo;

    // 监听方法
    _eventOnDtk = eventBus.on<EventQuestionOnDtk>().listen((event) {

      if (event.index < _total) {
        _dtkTz = true;
        _pageController.jumpToPage(event.index);
      }
    });
    _eventOnYJMS = eventBus.on<EventQuestionOnYJMS>().listen((event) {

      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();

    // 结束时，缓存设置相关数据

    PracticeDao.saveSzInfo(szUtilComm.szInfo);
    dataUtilComm.paperData = null;
    _eventOnDtk.cancel();
    _eventOnYJMS.cancel();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    // 管理系统后退手势组件
    return PopScope(
      // 内容显示
      child: _scaffoldItem(),
      // 禁用系统后退手势。默认值为true，表示后退手势照常发生。
      canPop: false,
      // 系统后退手势发生时调用
      onPopInvoked: _onPopInvokeFun,
      // onPopInvokedWithResult: (bool didPop, String? result) {
      //
      // },
    );
  }

  /// 页面内容
  _scaffoldItem() {
    return Scaffold(
      backgroundColor: getColorWhite1(szYjms: szUtilComm.szInfo.yjms),
      body: FutureBuilder<Map<String, dynamic>>(
        future: _futureInit,
        builder: (
            BuildContext context,
            AsyncSnapshot<Map<String, dynamic>> snapshot,
            ) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (_init) {
              Map<String, dynamic> map = snapshot.data!;
              if (!map["suc"]) {
                // 数据加载失败
                WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                  if (map["msg"] != null && map["msg"] != "") {
                    ToastUtil.show(context: context, msg: map["msg"]);
                  }
                  Navigator.pop(context);
                });
              } else {
                dataUtilComm.paperData = map["data"];
                _total = dataUtilComm.paperData!.dtkList.length;
                _pageController = PageController(
                  initialPage: dataUtilComm.paperData!.lastIndex,
                  keepPage: true,
                );
              }
              _init = false;
            }
            return _content();
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }

  /// 内容显示方法
  _content() {
    var padding = MediaQuery.of(_context).padding;
    double height =
        MediaQuery.of(context).size.height - padding.top - padding.bottom;
    return Container(
      margin: EdgeInsets.only(top: padding.top, bottom: padding.bottom),
      child: SingleChildScrollView(
        child: SizedBox(
          width: MediaQuery.of(context).size.width,
          height: height,
          // height: 100,
          child: Column(
            children: [
              QuestionTitleWidget(
                total: _total,
                type: _type,
                name: dataUtilComm.paperData?.name ?? "",
                onTapFunType: _onTapFunType,
              ),
              hiSpace(height: 4),
              Expanded(
                child: _contentPage(),
              ),
              QuestionBottomWidget(
                type: _type,
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 题目切换方法
  _onTapFunType(QuestionTypeEnum value) {
    setState(() {
      _type = value;
    });
  }

  /// 显示内容方法
  _contentPage() {
    return PageView(
      // 当页面选中后回调这个方法，参数【index】是当前页面角标索引，从0开始
      onPageChanged: (int index) {

        // 发起广播
        eventBus.fire(EventQuestionOnPage(
          index: index,
          type: _type,
          dtkTz: _dtkTz,
        ));
        if (_dtkTz) {
          _dtkTz = false;
        }
      },
      // false 表示从第一页开始滑动
      reverse: false,
      // 滑动到页面底部无回弹效果
      physics: const BouncingScrollPhysics(),
      // 横向滑动切换
      scrollDirection: Axis.horizontal,
      // 页面控制器
      controller: _pageController,
      // 所有页面
      children: _pageList(),
    );
  }

  /// 滑动的所有页面
  _pageList() {
    List<Widget> widgets = [];
    for (int i = 0; i < _total; i++) {
      widgets.add(StemPage(
        type: _type,
        quesInit: widget.quesInit,
        index: i,
      ));
    }
    return widgets;
  }

  /// 退出发生时调用，
  /// didPop 表示是否退出，true已退出，false未退出
  void _onPopInvokeFun(bool didPop) {

    if (!didPop) {
      questionBackFun(
        context: _context,
        dataModel: dataUtilComm.dataModel,
        paperDataModel: dataUtilComm.paperData!,
      );
    }
  }
}
